package com.doublepointer;

class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        char[][] grid =  {
                {'1','1','1'},
                {'0','1','0'},
                {'1','1','1'}
        };
        int i = solution.numIslands(grid);
        System.out.println(i);
    }

    public int numIslands(char[][] grid) {
        int count = 0;
        char tmp;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                tmp = grid[i][j];
                if (tmp == '1' || tmp == '2') {
                    getFlag(i, j, grid);
                }
                if (tmp == '1') {
                    count++;
                    grid[i][j] = '2';
                }
            }
        }
        return count;
    }

    private void getFlag(int i, int j, char[][] grid) {
        if (i >= 0 && j >= 0 && i < grid.length && j < grid[0].length) {
            if (grid[i][j] == '0' || grid[i][j] == '2') return;
            if (grid[i][j] == '1')
                grid[i][j] = '2';
            getFlag(i - 1, j, grid);
            getFlag(i + 1, j, grid);
            getFlag(i, j - 1, grid);
            getFlag(i, j + 1, grid);

        }
        return;
    }
}
